﻿using Alison.Tools.HttpContact.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Alison.EFCore;
using Alison.EFCore.Dto;

namespace Alison.Service
{
	public class BasicService : IBasicService
	{
		private readonly ILogger<BasicService> _logger;
		public BasicService(ILogger<BasicService> logger) {
			_logger = logger;
		}

		public async Task<ApiResponse> Add(BasicDto dto) {
			try {
				using var db = new AlisonDbContext();
				var model = await db.Basics.AddAsync(new EFCore.Entity.Basic() {
					Createby = dto.CreateBy,
					Createdate = DateTime.Now,
					Datacode = dto.DataCode,
					Englishname = dto.EnglishName,
					Nativename = dto.NativeName,
					Typecode = dto.TypeCode
				});
				var ok = await db.SaveChangesAsync();
				return new ApiResponse(200, ok);
			} catch (Exception ex) {
				_logger.LogError(ex, "");
				return new ApiResponse(500, ex.Message);
			}
		}

		public async Task<ApiResponse> Delete(int id) {
			try {
				using var db = new AlisonDbContext();
				var model = await db.Basics.FirstOrDefaultAsync(t => t.Id.Equals(id));
				if (model == null)
					return new ApiResponse(201, "获取不到有效数据");

				db.Entry(model).State = EntityState.Deleted;
				var ok = await db.SaveChangesAsync();
				return new ApiResponse(200, ok);

			} catch (Exception ex) {
				_logger.LogError(ex, "");
				return new ApiResponse(500, ex.Message);
			}
		}

		public async Task<ApiResponse> GetAll(BasicDto dto) {
			try {
				using var db = new AlisonDbContext();
				var model = await db.Basics.Where(t => t.Nativename.Contains(dto.NativeName) ||
				string.IsNullOrWhiteSpace(dto.NativeName)).ToListAsync();

				return new ApiResponse(200, model.OrderBy(t => t.Id));
			} catch (Exception ex) {
				_logger.LogError(ex, "");
				return new ApiResponse(500, ex.Message);
			}
		}

		public async Task<ApiResponse> Save(BasicDto dto) {
			try {
				using var db = new AlisonDbContext();
				var model = await db.Basics.FirstOrDefaultAsync(t => t.Id.Equals(dto.Id));
				if (model==null)
					return new ApiResponse(201, "获取不到有效数据");

				model.Lastupdate = DateTime.Now;
				model.Lastupdateby = dto.LastUpdateBy;
				model.Nativename = dto.NativeName;
				model.Typecode = dto.TypeCode;
				model.Datacode = dto.DataCode;
				model.Englishname = dto.EnglishName;

				db.Entry(model).State = EntityState.Modified;
				var ok = db.SaveChangesAsync();

				return new ApiResponse(200, ok);
			} catch (Exception ex) {
				_logger.LogError(ex, "");
				return new ApiResponse(500, ex.Message);
			}
		}
	}
}
